package car.Postal.Grimentz;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class HttpClient {
	
	 static DefaultHttpClient httpclient = null;
	 static List<Cookie> cookies = null;
	 static UrlEncodedFormEntity p_entity = null;
	 static InputStream is; 
	 public static String get(String sUrl) throws ClientProtocolException, IOException {
	
		 String result;
		 String CleanUrl = sUrl;
     	// get rid of ' '
     	 CleanUrl =  CleanUrl.replace(" ", "%20");
     	 
		 String Data = null;
		 if( httpclient == null)
			 httpclient = new DefaultHttpClient(); 
		
		// HttpGet  post = new HttpGet(CleanUrl); 
		  HttpPost  post = new HttpPost(CleanUrl); 
		  
		 HttpResponse response = httpclient.execute(post); 
		 cookies = httpclient.getCookieStore().getCookies();

		/* if (cookies.isEmpty()) { 
	            System.out.println("None"); 
	        } else { 
	            for (int i = 0; i < cookies.size(); i++) { 
	                System.out.println("- " + cookies.get(i).toString()); 
	            } 
	        } 
		 *///ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
		 //response.getEntity().writeTo(ostream);  
		 is = response.getEntity().getContent(); 

		//convert response to string 
		 result="";
		try{ 

		BufferedReader reader = new BufferedReader(new 
		InputStreamReader(is,"iso-8859-1"),8); 
		StringBuilder sb = new StringBuilder(); 
		String line = null; 
		while ((line = reader.readLine()) != null) { 
			sb.append(line + "\n"); 
		} 
		result = sb.toString();

		}catch(Exception e){ 

			//TODO deal with the exception
			Log.e("log_tag", "Error converting result "+e.toString()); 

	 } 

		
		 return result;
	
		
	}
}
